let prefix = '';
new Vue({
    el: '#app',
    data() {
        return {
            activePath: '',
            dataDialog: false,
            showAvatar: true,
            loading: false,
            pwdDialog: false,
            editableTabsValue: '',
            systemName: '',
            searchText: '',
            currentTime: '',
            editableTabs: [],
            sysUser: {},
            sysMenu: [],
            buttons: [],
            unReadNum: 0,
            avatar: '',
            uploadUrl: '/common/upload/file',
            uploadHeaders: '',
            uploadData: {'module': '1'},
            dataForm: {
                id: '',
                sex: '',
                birthDate: '',
                phone: '',
                province: '',
                city: '',
                area: '',
                address: '',
                avatar: ''
            },
            dataFormRules: {
                sex: [
                    {required: true, message: '请选择', trigger: 'blur'}
                ],
                birthDate: [
                    {required: true, message: '请选择', trigger: 'blur'}
                ],
                phone: [
                    {required: true, message: '请输入', trigger: 'blur'},
                    {min: 11, max: 11, message: '手机号码格式不正确', trigger: 'blur'}
                ]
            },
            pwdForm: {
                oldPwd: '',
                newPwd: '',
                confirmPwd: ''
            },
            pwdFormRules: {
                oldPwd: [
                    {required: true, message: '请输入', trigger: 'blur'},
                    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                ],
                newPwd: [
                    {required: true, message: '请输入', trigger: 'blur'},
                    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                ],
                confirmPwd: [
                    {required: true, message: '请输入', trigger: 'blur'},
                    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
                ]
            },
            regionList: []
        }
    },
    computed: {

        formattedTime: function () {
            var date = new Date();
            var year = date.getFullYear();
            var month = ("0" + (date.getMonth() + 1)).slice(-2);
            var day = ("0" + date.getDate()).slice(-2);
            var hours = ("0" + date.getHours()).slice(-2);
            var minutes = ("0" + date.getMinutes()).slice(-2);
            var seconds = ("0" + date.getSeconds()).slice(-2);
            return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
        }
    },
    created() {
        this.updateTime();
        setInterval(this.updateTime, 1000);
        this.getConfigInfo()
        this.getMessageUnRead()
        this.loading = true
        getUserInfo({}).then((res) => {
            if (res.code === '200') {
                this.loading = false;
                this.sysUser = JSON.parse(JSON.stringify(res.data.sysUser));
                this.sysMenu = JSON.parse(JSON.stringify(res.data.sysMenu));
                this.parseTreeJson(res.data.sysMenu);
                this.avatar = this.sysUser.avatar;
                localStorage.setItem("avatar", this.avatar)
                localStorage.setItem("userId", this.sysUser.id)
                localStorage.setItem("mars-sysMenu", JSON.stringify(res.data.sysMenu))
                localStorage.setItem("mars-sysUser", JSON.stringify(res.data.sysUser))
                localStorage.setItem('mars-sysButtons', JSON.stringify(this.buttons));
                this.addTab('首页', '/home/home.html');
            } else {
                this.loading = false;
            }
        }).then(() => {
            this.initSocket()
        });

    },
    mounted: {},
    watch: {
        searchText(newText) {
            if (newText) {
                let menus = JSON.parse(localStorage.getItem("mars-sysMenu"));
                this.sysMenu = menus.filter(function (item) {
                    return item.menuName.toLowerCase().includes(newText.toLowerCase());
                });
            } else {
                this.sysMenu = JSON.parse(localStorage.getItem("mars-sysMenu"));
            }

        }
    },
    methods: {
        getMessageUnRead() {
            requests.get("/message/unRead").then(res => {
                if (res.code === '200') {
                    this.unReadNum = res.data
                }
            })
        },
        mineNotifyList() {
            openMiddlePage('查看通知', '/admin/sysNotify/mineSysNotify.html', this);
        },
        initSocket() {
            var that = this;
            var socket;
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
                var socketUrl = BASE_URL + "/websocket/" + localStorage.getItem("userId");
                socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
                console.log(socketUrl);
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
                socket = new WebSocket(socketUrl);
                //打开事件
                socket.onopen = function () {
                    console.log("websocket已打开");
                };
                //获得消息事件
                socket.onmessage = function (msg) {
                    if (msg.data !== '' || msg.data !== null) {
                        let message = JSON.parse(msg.data)
                        that.unReadNum = message.msgNumber;
                        Vue.prototype.$notify({
                            title: '通知',
                            type: 'success',
                            position: 'bottom-right',
                            message: message.content,
                            duration: 2000
                        })
                    }
                };
                socket.onclose = function () {
                    console.log("websocket已关闭");
                };
                socket.onerror = function () {
                    console.log("websocket发生了错误");
                }
            }
        },
        parseTreeJson(treeNodes) {
            for (let i = 0; i < treeNodes.length; i++) {
                if (treeNodes[i].url) {
                    this.buttons.push(treeNodes[i].url);
                }
                let child = treeNodes[i].children;
                if (child && child.length > 0) {
                    this.parseTreeJson(child);
                }
            }
        },
        updateTime() {
            var date = new Date();
            var year = date.getFullYear();
            var month = ("0" + (date.getMonth() + 1)).slice(-2);
            var day = ("0" + date.getDate()).slice(-2);
            var hours = ("0" + date.getHours()).slice(-2);
            var minutes = ("0" + date.getMinutes()).slice(-2);
            var seconds = ("0" + date.getSeconds()).slice(-2);
            this.currentTime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
        },
        getConfigInfo() {
            requests.get("/admin/sysConfig/sysInfo").then(res => {
                if (res.code === '200') {
                    this.systemName = res.data.systemName
                    localStorage.setItem("system-name", this.systemName)
                }
            })
        },
        handleCommand(cmd) {
            if (cmd === 'updateData') {
                this.dataForm = JSON.parse(localStorage.getItem("mars-sysUser"));
                openPage('修改用户信息', '/home/userInfo.html', this);
            } else if (cmd === 'updatePwd') {
                openPage('修改密码', '/home/update-password.html', this);
            } else if (cmd === 'logout') {
                requests.post('/logout').then((res) => {
                    if (res.code === '200' || res.code === '9999') {
                        localStorage.clear();
                        parent.location.href = '/login';
                    }
                });
            }
        },
        addTab(tabName, tabUrl) {
            let isExist = false;
            this.editableTabs.forEach((tab, index) => {
                if (tab.title === tabName) {
                    isExist = true;
                    return;
                }
            });
            if (isExist) {
                this.editableTabsValue = tabUrl;
                return;
            }
            this.editableTabs.push({
                title: tabName,
                name: tabUrl,
                content: prefix + tabUrl
            });
            this.editableTabsValue = tabUrl;
            location.hash = '' + this.editableTabsValue;
        },
        clickTab(tab, event) {
            location.hash = '' + tab.name;
            this.activePath = tab.name;
        },
        removeTab(tabName) {
            let tabs = this.editableTabs;
            let activeName = this.editableTabsValue;
            if (activeName === tabName) {
                tabs.forEach((tab, index) => {
                    if (tab.name === tabName) {
                        let nextTab = tabs[index + 1] || tabs[index - 1];
                        if (nextTab) {
                            activeName = nextTab.name;
                        }
                    }
                });
            }
            this.editableTabsValue = activeName;
            this.editableTabs = tabs.filter(tab => tab.name !== tabName);
            location.hash = '' + this.editableTabsValue;
            this.activePath = this.editableTabsValue;
        },
        handleAvatarSuccess(idx, res, file, name) {
            if (res.code === '200') {
                console.log(res)
                this.dataForm.avatar = res.data;
            }
        },
        beforeAvatarUpload(file) {
            let isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过2MB!');
            }
            return isLt2M;
        },
        dataFormSubmit() {
            this.$refs.dataForm.validate((valid) => {
                if (valid) {
                    this.dataDialog = false;
                    let param = this.dataForm;
                    requests.post('/updateInfo', JSON.parse(JSON.stringify(param)))
                        .then((res) => {
                            if (res.code === '200') {
                                let sysUser = JSON.parse(localStorage.getItem("mars-sysUser"));
                                localStorage.setItem('mars-sysUser', JSON.stringify(sysUser));
                                this.$notify({
                                    title: '成功',
                                    message: '修改成功，请刷新',
                                    type: 'success'
                                });
                            } else {
                                this.$message.error(res.message);
                            }
                        });
                } else {
                    return false;
                }
            });
        },
        pwdFormSubmit() {
            this.$refs.pwdForm.validate((valid) => {
                if (valid) {
                    let param = this.pwdForm;
                    requests.post('/pwd/update', JSON.parse(JSON.stringify(param)))
                        .then((res) => {
                            if (res.code === '200') {
                                parent.layer.msg('修改成功');
                                this.pwdDialog = false;
                            } else {
                                parent.layer.msg(res.message);
                            }
                        });
                } else {
                    return false;
                }
            });
        }
    },

});
